C++ function returning pointer, why does this work ? [migrated]

Posted by nashmaniac on Programmers See other posts from Programmers or by nashmaniac
Published on 2012-11-09T15:55:47Z Indexed on 2012/11/09 17:20 UTC
Read the original article Hit count: 173

Filed under:
|
|

So heres a simple c++ function what it does it take an array of characters as its argument and a integer n and then creates a new character array with only n elements of the array.

char * cutString(char * ch , int n){

  char * p = new char[n];
  int i ;
  for(i = 0 ; i < n ; i++)
         p[i] = ch[i];
  while(i <= n ){
    p[i++] = '\0';
  }
  return p ;

}

this works just fine but if I change char * p = new char[n]; to char p[n]; I see funny characters what happens ? What difference does the former make also p is a temporary variable then how does the function returns it alright ?

© Programmers or respective owner

Related posts about c++

Related posts about memory